package com.tdx.blog_nowcoder.controller;

import com.tdx.blog_nowcoder.entity.DiscussPort;
import com.tdx.blog_nowcoder.service.ElasticsearchService;
import com.tdx.blog_nowcoder.service.LikeService;
import com.tdx.blog_nowcoder.service.UserService;
import com.tdx.blog_nowcoder.utils.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.tdx.blog_nowcoder.constant.CommentReplyConstant.ENTITY_TYPE_COMMENT;

/**
* @description: TODO
* @author 何可人
* @date 2022/7/8 17:27
* @version 1.0
*/
@Controller
public class DiscussPostSearchController {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    // search?keyword=xxx
    @RequestMapping(path = "/search", method = RequestMethod.GET)
    public String search(String keyword, Page page, Model model) throws Exception {
        System.out.println(keyword);
        // 分页信息
        page.setPath("/search?keyword=" + keyword);
        page.setTotalPageNums(elasticsearchService.getHitcount(keyword));

        // 搜索帖子
        List<DiscussPort> searchResult =
                elasticsearchService.highlightQuery(keyword, page.getOffset(), page.getPerPageSize());
        // 聚合数据
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (searchResult != null) {
            for (DiscussPort post : searchResult) {
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("post", post);
                // 作者
                map.put("user", userService.selectUserById(post.getUserId()));
                // 点赞数量
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, post.getId()));

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("keyword", keyword);

        return "/site/search";
    }
}
